package cn.tedu.charging.cost.dao.repository.impl;

import cn.tedu.charging.common.pojo.utils.JsonUtils;
import cn.tedu.charging.cost.dao.repository.CostRuleCacheRepository;
import cn.tedu.charging.cost.pojo.po.CostRulePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

@Repository
public class CostRuleCacheRepositoryImpl implements CostRuleCacheRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public List<CostRulePO> getCostRulesByStationId(Integer stationId) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String CostRuleKey = "COST_RULE_KEY_:" + stationId;
        Serializable serializable = valueOperations.get(CostRuleKey);
        if (serializable != null) {
            return getCostRulePOS(serializable);
        }
        return Collections.emptyList();
    }

    @Override
    public void saveCostRule2Redis(Integer stationId, List<CostRulePO> costRulePOS) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String CostRuleKey = "COST_RULE_KEY_" + stationId;
        String json = JsonUtils.toJson(costRulePOS);
        valueOperations.set(CostRuleKey, json);
    }

    private List<CostRulePO> getCostRulePOS(Serializable serializable){
        List<CostRulePO> costRulePOS = new ArrayList<>();
        List<LinkedHashMap<String,CostRulePO>> mapList = JsonUtils.fromJson(String.valueOf(serializable), List.class);
        mapList.forEach(map -> {
            CostRulePO costRulePO = JsonUtils.convertValue(map, CostRulePO.class);
            costRulePOS.add(costRulePO);
        });
        return costRulePOS;
    }
}
